$(function() {
	//初始化加载
	menuCate();
	Handlebars.registerHelper('if_eq', function(v1, v2, opts) {
		if(v1 == v2)
			return opts.fn(this);
		else
			return opts.inverse(this);
	});
	Handlebars.registerHelper('if', function(v1, v2, opts) {
		if(v1 <= v2)
			return opts.fn(this);
		else
			return opts.inverse(this);
	});
	proType();		//搜索的类型
	monType();		//月份类型
	
	filtermain();	//条件
	sortmain();		//排序
	searchbut();	//搜索
	
	wareMain();		//商品数据
	
	
	/*分页初始化*/
	var aa = $(".pagelist").attr("length");
	$('.pagelist').pagination({
		pageCount: aa,
		jump: false,
		coping: true,
		homePage: '首页',
		endPage: '末页',
		prevContent: '上页',
		nextContent: '下页',
		callback: function(api) {
			
			var pagecount = $(".pagelist").attr('length');
			api.setPageCount(pagecount);
			wareMain(api.getCurrent());
		}
	});
	
	/*搜索点击事件*/
	$("#hearSearch").click(function(){
		
		
		wareMain();
	});
	
});


//分类
function menuCate() {
	var menuTmpl = $('#menu-template').html();
	var menuPage = Handlebars.compile(menuTmpl);
	$.ajax({
		url: C.interface.categoryInter,
		type: 'get',
		dataType: 'json',
		data: {},
		success: function(data) {
			if(data.code == "10000") {
//				console.log(data.data)
				$("#menulist").html(menuPage(data.data));
				clickBut();
				tiao();
			}
		}
	})
}


//跳过来的分类
//console.log(window.location.href.split("?categoryId=")[1])
function tiao() {
	categoryId = window.location.href.split("?categoryId=")[1];
	$(".warecon").empty();
	wareMain();
}


/*条件搜索分类*/
var categoryId = '';
function clickBut() {
	$("#menulist .col-md-2").click(function() {

		$("#menulist .col-md-2").removeClass('colorZ');
		$(this).addClass('colorZ');
		categoryId = $(this).attr("categoryId");
		$(".warecon").empty();
		wareMain();
	});
}

//搜索的类型
var type='';
function proType() {
	$(".goodtype .col-md-2").click(function() {
		$(".goodtype .col-md-2").removeClass('colorZ');
		$(this).addClass('colorZ');
		type = $(this).html();
		if(type == "京东"){
			type = 'jd'
		}else if(type == "友惠家"){
			type = 'yh'
		}else if(type == "全部"){
			type = ' '
		}
		$(".warecon").empty();
		wareMain();
		
	})
}
//月份点击事件
var time = '';
function monType() {
	$(".monthType .col-md-2").click(function() {
		$(".monthType .col-md-2").removeClass('colorZ');
		$(this).addClass('colorZ');
		time = $(this).html();
		if(time == "今日更新"){
			time = 'curren';
		}else if(time == "一周更新"){
			time = 'week';
		}else if(time == "一月更新"){
			time = 'month';
		}else if(time == "一季度更新"){
			time = 'quarter';
		}
		$(".warecon").empty();
		wareMain();
	})
}

//筛选
var price,commission,commissionShare;
function filtermain(){
	$("#scrbut").click(function(){
		//价钱
		price = $("#price").val();
		commission = $("#commission").val();
		commissionShare = $("#commissionShare").val();
		$(".warecon").empty();
		wareMain();
	})
}

/*排序新机*/
var pricesort = 'priceDesc';
var samesort = '';
var sameobj;
var total = 'totalSalesDesc'
function sortmain(){
	$("#ordermain .col-md-2").click(function(){
		
		var thisOb = $(this);
		var px = thisOb.attr("id");
		
		if(px == 'zonghe'){
			samesort = 'zonghe';
		}else{
			/*判断正序倒叙*/
			if(thisOb.hasClass("myon")){
				samesort = px+"Asc";
				thisOb.removeClass("myon");
				thisOb.addClass("myoff");
			}else if(thisOb.hasClass("myoff")){
				samesort = px+"Desc";
				thisOb.removeClass("myoff");
				thisOb.addClass("myon");
			}
		}
		
		/*添加样式*/
		$("#ordermain .col-md-2").removeClass('colorZ');
		thisOb.addClass('colorZ');
		
		/*从新加载数据*/
		$(".warecon").empty();
		wareMain();
	});
}
//搜索
var keyword = ''
function  searchbut(){
  	var pos,str,parastr;
	str = window.location.href;
	str = decodeURI(str);  //对参数进行decodeURI解码
	var tag = "?";
	if(str.indexOf(tag)!=-1){
		pos = str.indexOf("?");
		parastr = str.substring(pos+1);
		parastr = parastr.replace("searchVal=","");
		
		$(".search-input").val(parastr);
		
		$(".warecon").empty();
		wareMain();
	}
}

//商品数据信息读取
var count=10;
function wareMain(page) {
	var wareTmpl = $('#ware-template').html();
	var warePage = Handlebars.compile(wareTmpl);
	var b;
	
	$.ajax({
		url: C.interface.choisegood,
		type: 'get',
		dataType: 'json',
		
		data: {
			length: 8,
			start: page,
			categoryCode:categoryId,
			type:type,
			keyword:$(".search-input").val(),
			typeTime:time,
			price:price,
			commission:commission,
			commissionShare:commissionShare,
			orderType:samesort
		},
		success: function(data) {
//			console.log(data)
			if(data.code == "10000") {
				var total = data.data.total;
				count = Math.ceil(total / 8); //算总数
				
				$(".pagelist").attr('length',count); // 初始化加载list
				
				$(".warecon").html(warePage(data.data.list));
//				$(".goodsContent").click(function(){
//					var id= $(this).attr("data_id");
//					window.location.href="goodsDetails.html?id="+id
//				});

				$(".caption").click(function(){
					var id= $(this).attr("data_id");
					window.location.href="goodsDetails.html?id="+id
				});
				$(".goodsImages").click(function(){
					var id= $(this).attr("data_id");
					window.location.href="goodsDetails.html?id="+id
				});
				/* 商品模块hover显示按钮 */
				$(".goodsContent").mouseover(function(){
					$(this).find(".btnImagesTop").show();
				});
				$(".goodsContent").mouseout(function(){
					$(this).find(".btnImagesTop").hide();
				});
				
				$('.fuzhi').on("mouseover",function(){
					   var index = $('.fuzhi').index($(this));
					   $('.btnImagesTopp').eq(index).show();
					})
					$('.fuzhi').on("mouseleave",function(){
					   var index = $('.fuzhi').index($(this));
					   $('.btnImagesTopp').eq(index).hide();
					})
				
				$(".btn-copyLink").qtip({ 
					content:{  
                		text:function (){
                			var str = $(this).attr("id");
                			var arr=new Array();
							arr = str.split(',');
							var img =  arr[0];
							var goodsName =  arr[1];
							var price =  arr[2];
							var conPrice =  arr[3];
							var linkUrl =  arr[4];
							var skUrl =  'http://item.jd.com'+arr[5]+'/.html';
                			var con = '<img class="goodsImages" width="120px" src="'+img+'" alt="..."><p>'+goodsName+'</p><p>京东价：'+price+'元</p><p>券后价：'+conPrice+'元</p>'+linkUrl+'<p>领券：</p><p></p><p>抢购：</p>'+
                			'<p>'+ skUrl +'</p>'
                			return con;
                		}
                	}
					/*content: '<img class="goodsImages" width="120px" src="'+img+'" alt="..."><p>【买2送1 国妆特证】【一喷一抹 30天祛味断根】植物草本萃取，天然成分不过敏不伤肤！</p><p>芊茗草狐臭液喷剂30天根治狐臭</p><p>京东价：48元</p><p>券后价：29元</p><p>领券：</p><p>http://coupon.m.jd.com/coupons/show.action?key=ce63374f6522472584b0c8b0acc3e63d&roleId=10558331&to=mall.jd.com/index-143672.html</p><p>抢购：</p><p>\rhttp://item.jd.com/21590088027.html</p>',*/
				}); 
				var clipboard = new Clipboard('.btn-copyLink');
			    clipboard.on('success', function(e) {
//			        console.log(e);
			    });
			
			    clipboard.on('error', function(e) {
			        console.log(e);
			    });
				$(".extdenbut").click(function(){
					
					var token = localStorage.getItem('token');
					//	console.log(token)
						
					if (token != "" && token != null){
						
						$(".goodsContent").unbind()
			   		var id = $(this).attr("extend_id");
						window.location.href = "back/chainTool/chainTool.html?id="+id
//						
						
					}else{
						window.location.href = 'login.html'
					}
					
					
			   		
			   		
			   })
			}
		}
	});
}


$(".lian").click(function(){
		var url = window.location.pathname; 
		var token = localStorage.getItem('token');
					//	console.log(token)
						
	if (token != "" && token != null){
					
			window.location.href = "back/chainTool/chainTool.html"
						
	}else{
		window.location.href = 'login.html'
	}
					
			   		 
})

//		QQ群链接
		$('.ruanjain').click(function(){
				window.location.href ='https://jq.qq.com/?_wv=1027&k=5EP8Afe'
			})
			$('.guanfang').click(function(){
				window.location.href ='https://jq.qq.com/?_wv=1027&k=5sOPc0B'
			})
		
		//链接工具
		$('.tiao').click(function(){
				window.location.href = 'http://chat56.live800.com/live800/chatClient/chatbox.jsp?companyID=944015&configID=155782&jid=9694995927'
		})
		
var myDate = new Date();
			//获取当前年
			var year=myDate.getFullYear();
			$('.shi').text(year)